# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError

from web import models
from web.forms.bootstrap import BootStrapForm
from django import forms

from web.forms.widgets import ColorRadioSelect


class ProjectForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']
    
    # 1. 重写字段
    # desc = forms.CharField(widget=forms.Textarea())
    
    class Meta:
        model = models.Project
        fields = ['project_name', 'color', 'desc']
        
        # 2. 重写字段 通过attrs传递属性给标签  默认的字段都可以修改
        widgets = {
            'desc': forms.Textarea(attrs={'xxx': 2}),
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
    
        self.request = request
    
    def clean_project_name(self):
        """项目校验"""
        
        project_name = self.cleaned_data['project_name']
        # 1. 创建的项目是否已存在
        exist = models.Project.objects.filter(project_name=project_name, creator=self.request.tracer.user).exists()
        if exist:
            raise ValidationError('项目已存在')
        # 2. 当前用户是否还有额度进行创建项目
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限，请购买套餐')
        return project_name
